/*

  The MIT License

  Copyright (c) 2008 - 2010. Dimarik

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

package ru.goodcore.display
{

import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.errors.IllegalOperationError;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLRequest;
import flash.system.LoaderContext;
import flash.utils.ByteArray;
import flash.utils.Endian;

import ru.goodcore.utils.getDefinitionNames;


/**
 * 
 * 
 * @author				Dimarik
 * @version				1.2
 * @langversion			3.0
 * @playerversion		9.0
 * 
 */
public final class GIFLoaderAdv extends Loader {

	//-------------------------------------------------------------------------
	//
	//   Class methods
	//
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	//
	//   Constructor
	//
	//-------------------------------------------------------------------------

	/**
	 * Constructor
	 */
	public function GIFLoaderAdv(
								smooth:			Boolean = false, 
								useDelays:		Boolean = true, 
								stageFrameRate:	uint = 0
	) {
		super();
		this._smooth	= smooth;
		this._useDelays	= useDelays;
		this._stageFPS	= stageFrameRate & 0xFF;

		var li:LoaderInfo = this.contentLoaderInfo; // super, но парсер лох.

		li.addEventListener(Event.OPEN,							this.handler_monitor,	false, int.MAX_VALUE);
		li.addEventListener(ProgressEvent.PROGRESS,				this.handler_monitor,	false, int.MAX_VALUE);
		li.addEventListener(IOErrorEvent.IO_ERROR,				this.handler_monitor,	false, int.MAX_VALUE);
		li.addEventListener(Event.INIT,							this.handler_monitor,	false, int.MAX_VALUE);
		li.addEventListener(Event.UNLOAD,						this.handler_monitor,	false, int.MAX_VALUE);
		li.addEventListener(HTTPStatusEvent.HTTP_STATUS,		this.handler_monitor,	false, int.MAX_VALUE);
		li.addEventListener(Event.COMPLETE,						this.handler_monitor,	false, int.MAX_VALUE);

	/*
		li.addEventListener(Event.OPEN,							this.handler_passOnLoadPhase,	false, int.MAX_VALUE);
		li.addEventListener(Event.INIT,							this.handler_skipOnLoadPhase,	false, int.MAX_VALUE);
		li.addEventListener(Event.UNLOAD,						this.handler_passOnLoadPhase,	false, int.MAX_VALUE);
		li.addEventListener(ProgressEvent.PROGRESS,				this.handler_passOnLoadPhase,	false, int.MAX_VALUE);
		li.addEventListener(IOErrorEvent.IO_ERROR,				this.handler_passOnLoadPhase,	false, int.MAX_VALUE);
		li.addEventListener(HTTPStatusEvent.HTTP_STATUS,		this.handler_skipOnLoadPhase,	false, int.MAX_VALUE);
	*/
		li.addEventListener(Event.COMPLETE,						this.handler_complete,			false, int.MAX_VALUE);


	}

	//-------------------------------------------------------------------------
	//
	//   Overridden properties: Loader
	//
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	//
	//   Properties
	//
	//-------------------------------------------------------------------------
	
	//---------------------------------
	//  qname
	//---------------------------------
	/**
	 * @private 
	 */
	private var _qname:			QName;

	public function set qname(value:QName):void {
		if (this._qname === value)
			return;

		this._qname = value;
	}

	public function get qname():QName {
		return this._qname;
	}

	//-------------------------------------------------------------------------
	//
	//   Private variables
	//
	//-------------------------------------------------------------------------

	/**
	 * @private 
	 */
	private var _loadPhase:		Boolean = true;


	/**
	 * @private 
	 */
	private var _smooth:		Boolean;

	/**
	 * @private 
	 */
	private var _useDelays:		Boolean;

	/**
	 * @private 
	 */
	private var _stageFPS:		uint;

	/**
	 * @private 
	 */
	private var _context:		LoaderContext;

	/**
	 * @private 
	 */
	private var _pattern:		uint;

	//-------------------------------------------------------------------------
	//
	//   Overridden methods: Loader
	//
	//-------------------------------------------------------------------------

	/**
	 * @inheritDoc
	 * @see Loader#load
	 *  
	 * @param request
	 * @param context
	 * 
	 */
	public override function load(request:URLRequest, context:LoaderContext = null):void {
		this._pattern = 7;

		this._loadPhase = true;

		if (context) {
			var copy:LoaderContext = this._context = new LoaderContext();
			copy.checkPolicyFile = context.checkPolicyFile;
			copy.applicationDomain = context.applicationDomain;
		}

		super.load(request, context);
	}

	/**
	 * @inheritDoc
	 * @see Loader#load
	 *  
	 * @param request
	 * @param context
	 * 
	 */
	public override function loadBytes(bytes:ByteArray, context:LoaderContext=null):void {
		this._loadPhase = false;

		if (context) {
			var copy:LoaderContext = this._context = new LoaderContext();
			copy.checkPolicyFile = context.checkPolicyFile;
			copy.applicationDomain = context.applicationDomain;
			this._context = copy;
		}

		this.loadGIF(bytes);
	}

	//-------------------------------------------------------------------------
	//
	//   Private methods
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	private function loadGIF(ba:ByteArray):void {
		var li:LoaderInfo = super.contentLoaderInfo;

		if ( !this._qname ) { // Не задан пакет и класс 
			var regExp:RegExp = /^.*?:\/\/(?P<url>.*)\/(?P<localName>.*)$/;
			var o:Object = li.url.match(regExp);
			var url:String = 'ru.goodcore.resource.$.' + String(o.url).replace(/\//g, '.');
			var localName:String = String(o.localName).replace(/\./g, '_');
			this._qname = new QName( url, localName );
		}

		if (super.stage && this._stageFPS == 0)
			this._stageFPS = super.stage.frameRate;

		var swf:SWFGIFMovieClipDocClass = new SWFGIFMovieClipDocClass(ba, this._qname, this._smooth, this._useDelays ? this._stageFPS : 0);
		super.loadBytes( swf, this._context );
		// FIRE unload
		// FIRE progress
		// FIRE progress
		// FIRE complete

		this._context = null;
		this._qname = null;
	}

	//-------------------------------------------------------------------------
	//
	//   Event handlers
	//
	//-------------------------------------------------------------------------

	/**
	 * @param event
	 */
	private function handler_monitor(event:Event):void {
		trace('handler_monitor:', event);
		
		var skip:	Boolean;
		var bit:	uint = 1;

		switch (event.type) {
			case Event.OPEN:
				bit <<= 0;
				break;

			case ProgressEvent.PROGRESS:
				bit <<= 1;
				break;

			case IOErrorEvent.IO_ERROR:
				bit <<= 2;
				break;

			case Event.INIT:
				bit <<= 3;
				break;

			case Event.UNLOAD:
				bit <<= 4;
				break;

			case HTTPStatusEvent.HTTP_STATUS:
				bit <<= 5;
				break;

			case Event.COMPLETE:
				bit <<= 6;
				break;

		}

		skip = Boolean( (this._pattern ^= bit) & bit );
		trace(bit.toString(2), skip, this._pattern.toString(2));

		if ( skip )
			event.stopImmediatePropagation();
	}

	/**
	 * @param event
	 */
	private function handler_skipOnLoadPhase(event:Event):void {
		if ( this._loadPhase ) {
			trace('stopped OnLoadPhase:', event);
			event.stopImmediatePropagation();
		} else {
			trace('passed OnBytesPhase:', event);
		}
	}

	/**
	 * @param event
	 */
	private function handler_passOnLoadPhase(event:Event):void {
		if ( !this._loadPhase ) {
			trace('stopped OnBytesPhase:', event);
			event.stopImmediatePropagation();
		} else {
			trace('passed OnLoadPhase:', event);
		}
	}

	/**
	 * 
	 * @param event
	 * 
	 */
	private function handler_complete(event:Event):void {
		trace('handler_complete:', event);
		if ( !this._loadPhase )
			return;

		event.stopImmediatePropagation();
		this._loadPhase = false;

		var ba:ByteArray = super.contentLoaderInfo.bytes;
		ba.endian = Endian.LITTLE_ENDIAN;

		// Читаем до 0xBF [17]h (DefineBitsJPEG4)
		while ( ba.readUnsignedByte() != 0xBF ) void;
		ba.position += 7;
		var len:uint = ba.readUnsignedInt(); // Размер гифки в байтах		
		ba.position += 2; // skip DeblockParam
		ba.readBytes(ba, 0, len);
		ba.position = 0;
		this.loadGIF(ba);
	}

}
}
